package services

import (
	"GOPAAS/internal/app/global"
	"GOPAAS/internal/app/model"
	"GOPAAS/internal/utils"
	"database/sql"
	"errors"
)

type GroupService struct {
	model.ResGroups
}

func GetGroupService(gid int64) *GroupService {
	db = getDB()
	var group model.ResGroups
	if gid > 0 {
		db.First(&group, gid)
	}
	return &GroupService{group}
}

type GroupInfo struct {
	model.ResGroups
	Category string
}

type GroupItem struct {
	Id         int64  `json:"id"`
	Name       string `json:"name"`
	Category   string `json:"category"`
	Share      string `json:"share"`
	CreateDate string `json:"create_date"`
}

// GetList 分组列表
func (g *GroupService) GetList(start int, length int, order string, sort string, category_id int, name string, share sql.NullBool, create_date_b string, create_date_e string, ids []int64) (res []GroupItem, total int64, err error) {
	db = getDB()
	res = make([]GroupItem, 0)
	data_query := db.Model(&model.ResGroups{})
	count_query := db.Model(&model.ResGroups{})
	if name != "" {
		data_query.Where("res_groups.name like ?", "%"+name+"%")
		count_query.Where("res_groups.name like ?", "%"+name+"%")
	}
	if category_id != 0 {
		data_query.Where("category_id= ?", category_id)
		count_query.Where("category_id= ?", category_id)
	}
	if share.Valid {
		data_query.Where("share= ?", share.Bool)
		count_query.Where("share= ?", share.Bool)
	}
	if create_date_b != "" && create_date_e != "" {
		create_date_b = create_date_b + " 00:00:00"
		create_date_e = create_date_e + " 23:59:59"
		data_query.Where("res_groups.create_date between ? and ?", create_date_b, create_date_e)
		count_query.Where("res_groups.create_date between ? and ?", create_date_b, create_date_e)
	}
	if len(ids) > 0 {
		data_query.Where("res_groups.id in ?", ids)
		count_query.Where("res_groups.id in ?", ids)
	}

	order = "res_groups." + order
	var app_str = order + " " + sort
	type JoinModel struct {
		model.ResGroups
		Category string
	}
	var result []JoinModel
	count_query.Count(&total)
	data_query.Joins("left join ir_module_category on res_groups.category_id=ir_module_category.id").Select("res_groups.*", "ir_module_category.name as category").Offset(start).Limit(length).Order(app_str).Find(&result)
	for _, v := range result {
		var share_name string
		if v.Share.Valid {
			if v.Share.Bool {
				share_name = "是"
			} else {
				share_name = "否"
			}
		}
		res = append(res, GroupItem{
			Id:         v.Id,
			Name:       v.Name,
			Category:   v.Category,
			Share:      share_name,
			CreateDate: v.CreateDate.Format("2006-01-02 15:04:05"),
		})
	}
	return
}

// GetIdList 分组id列表
func (g *GroupService) GetIdList(category_id int, name string, share sql.NullBool, create_date_b string, create_date_e string) (res []int64, err error) {
	db = getDB()
	res = make([]int64, 0)
	data_query := db.Model(&model.ResGroups{})
	if name != "" {
		data_query.Where("res_groups.name like ?", "%"+name+"%")
	}
	if category_id != 0 {
		data_query.Where("category_id= ?", category_id)
	}
	if share.Valid {
		data_query.Where("share= ?", share.Bool)
	}
	if create_date_b != "" && create_date_e != "" {
		create_date_b = create_date_b + " 00:00:00"
		create_date_e = create_date_e + " 23:59:59"
		data_query.Where("res_groups.create_date between ? and ?", create_date_b, create_date_e)
	}
	data_query.Select("res_groups.id").Order("id").Pluck("id", &res)
	return
}

// RemoveGroup 删除分组
func (g *GroupService) RemoveGroup() error {
	db = getDB()
	var g_user model.ResGroupsUsersRel
	var user_ids []int64
	db.Model(&g_user).Where("gid=?", g.Id).Pluck("uid", &user_ids)
	if len(user_ids) > 0 {
		return errors.New("分组下有用户，请先移除用户")
	}
	var group = g.ResGroups
	res := db.Delete(&group)
	return res.Error
}

// RemoveGroups 批量删除分组
func RemoveGroups(group_id_arr []int64) error {
	db = getDB()
	var g_user model.ResGroupsUsersRel
	var user_ids []int64
	db.Model(&g_user).Where("gid in ?", group_id_arr).Pluck("uid", &user_ids)
	if len(user_ids) > 0 {
		return errors.New("分组下有用户，请先移除用户")
	}
	var group model.ResGroups
	res := db.Delete(&group, group_id_arr)
	return res.Error
}

// CreateGroup 创建分组
func CreateGroup(info global.CreateGroupRequest, login_user_id int64) (gid int64, err error) {
	db = getDB()
	var group model.ResGroups
	db.Where("name = ?", info.Name).First(&group)
	if group.Id > 0 {
		err = errors.New("分组已存在")
		return
	}
	group = model.ResGroups{
		Name:       info.Name,
		CategoryId: info.CategoryId,
		Comment:    info.Comment,
		Share:      info.Share,
		ResCommon: model.ResCommon{
			CreateUid: login_user_id,
			WriteUid:  login_user_id,
		},
	}
	result := db.Select("Name", "CategoryId", "Comment", "Share").Create(&group)
	if result.Error != nil {
		err = result.Error
		return
	}
	gid = group.Id
	return
}

// UpdateGroup 修改分组
func (g *GroupService) UpdateGroup(info global.CreateGroupRequest, login_user_id int64) (err error) {
	db = getDB()
	var group model.ResGroups
	db.Where("name = ?", info.Name).Where("id<>?", g.Id).First(&group)
	if group.Id > 0 {
		err = errors.New("分组已存在")
		return
	}
	group = model.ResGroups{
		Name:       info.Name,
		CategoryId: info.CategoryId,
		Comment:    info.Comment,
		Share:      info.Share,
		ResCommon: model.ResCommon{
			Id:       g.Id,
			WriteUid: login_user_id,
		},
	}
	result := db.Select("Name", "CategoryId", "Comment", "Share").Save(&group)
	if result.Error != nil {
		err = result.Error
		return
	}
	return
}

// GetCategoryInfo 获取分类
func GetCategoryInfo(category_id int64) (result model.IrModuleCategory) {
	db = getDB()
	db.First(&result, category_id)
	return
}

// RemoveGroupUsers 删除分组用户
func (g *GroupService) RemoveGroupUsers(user_ids []int64) (err error) {
	db = getDB()
	db.Where("gid=? and uid in ?", g.Id, user_ids).Delete(&model.ResGroupsUsersRel{})
	return
}

// GetGroupUsers 获取分组所有用户
func GetGroupUsers(group_ids []int64) (user_ids []int64) {
	db = getDB()
	db.Model(&model.ResGroupsUsersRel{}).Where("gid in ?", group_ids).Pluck("uid", &user_ids)
	return
}

// AddGroupUsers 新增分组用户
func (g *GroupService) AddGroupUsers(user_ids []int64) (err error) {
	db = getDB()
	db.Where("gid=? and uid in ?", g.Id, user_ids).Delete(&model.ResGroupsUsersRel{})
	var guser = []model.ResGroupsUsersRel{}
	for _, user_id := range user_ids {
		guser = append(guser, model.ResGroupsUsersRel{g.Id, user_id})
	}
	result := db.Create(&guser)
	err = result.Error
	return
}

// IsGroupAdmin 是否有摸个模块的管理权限
func IsGroupAdmin(mange_group_ids []int64, group_ids []int64) bool {
	for _, v := range mange_group_ids {
		if utils.Int64InArray(group_ids, v) {
			return true
		}
	}
	return false
}
